package com.coldwindblows.blog.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.coldwindblows.blog.constant.WebConst;
import com.coldwindblows.blog.dto.Types;
import com.coldwindblows.blog.pojo.OptionDo;
import com.coldwindblows.blog.pojo.UserDo;
import com.coldwindblows.blog.service.IOptionService;
import com.coldwindblows.blog.service.IUserService;
import com.coldwindblows.blog.utils.AdminCommons;
import com.coldwindblows.blog.utils.Commons;
import com.coldwindblows.blog.utils.IPKit;
import com.coldwindblows.blog.utils.MapCache;
import com.coldwindblows.blog.utils.TaleUtils;
import com.coldwindblows.blog.utils.UUID;

/**
 * 自定义拦截器
 * Created by ColdWindBlows on 2018/07/07
 */
@Component
public class BaseInterceptor implements HandlerInterceptor {
	private static final Logger LOGGER = LoggerFactory.getLogger(BaseInterceptor.class);
	private static final String USER_AGENT = "user-agent";
	
	@Autowired
	private IUserService userService;
	
	@Autowired
	private IOptionService optionService;
	
	private MapCache cache = MapCache.single();
	
	@Autowired
	private Commons commons;
	
	@Autowired
	private AdminCommons adminCommons;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
	
		String uri = request.getRequestURI();
		
		LOGGER.info("UserAgent：{}", request.getHeader(USER_AGENT));
		LOGGER.info("用户访问地址：{},来路地址：{}", uri, IPKit.getIpAddrByRequest(request));
		
		// 请求拦截处理
		UserDo user = TaleUtils.getLoginUser(request);
		if(null == user) {
			Integer uid = TaleUtils.getCookieUid(request);
			if(null != uid) {
				// Cookie 可以伪造的，。存在安全隐患 TODO
				user = userService.queryUserById(uid);
				request.getSession().setAttribute(WebConst.LOGIN_SESSION_KEY, user);
			}
		}
		if(uri.startsWith("/admin") && !uri.startsWith("/admin/login") && !uri.startsWith("/admin/register") && null == user) {
			response.sendRedirect(request.getContextPath() + "/admin/login");
			return false;
		}
		// 设置get请求的token
		if(request.getMethod().equals("GET")) {
			String csrf_token = UUID.UU64();
			// 默认存储30分钟
			cache.hset(Types.CSRF_TOKEN.getType(), csrf_token, uri, 30 * 60);
			request.setAttribute("_csrf_token", csrf_token);
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object obj, ModelAndView mv)
			throws Exception {
		OptionDo op = optionService.getDetail("site_record");
		request.setAttribute("commons", commons);// 一些工具类和公共方法
		request.setAttribute("option", op);
		request.setAttribute("adminCommons", adminCommons);
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj, Exception exe)
			throws Exception {
		
	}

}
